<template>
  <div class="main">
    <div>
      <!-- <el-button
        type="danger"
        :icon="useRenderIcon('ep:delete')"
        :loading="delLoading"
        @click="resetAllUserPrice"
      >
        重置用户所有价格配置
      </el-button> -->
      <el-button type="success" @click="adjustUserCustom">
        批量调整服务的用户特定价格
      </el-button>
    </div>

    <CreateUserPriceDialog ref="createUserPriceDialogRef" @refresh="onSearch" />
    <MulitServicePriceDialog
      ref="mulitServicePriceDialogRef"
      :serviceTypes
      @refresh="onSearch"
    />
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="用户" prop="userId">
        <el-select
          ref="userSelectRef"
          v-model="form.userId"
          placeholder="请选择"
          filterable
          remote
          :remote-method="onKeywordInput"
          class="!w-[180px]"
          clearable
          @visible-change="onUserDropdownVisibleChange"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
          <template v-if="userLoading" #footer>
            <div class="text-center text-xs text-gray-500">
              <span>加载中...</span>
            </div>
          </template>
        </el-select>
      </el-form-item>

      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="请输入"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>

      <el-form-item label="服务类型" prop="serviceType">
        <el-select
          v-model="form.serviceType"
          placeholder="请选择"
          filterable
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in serviceTypes"
            :key="item.standardCode"
            :label="item.displayName"
            :value="item.standardCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="userId" label="用户ID" width="140" />
      <el-table-column prop="username" label="用户名称" width="180" />
      <el-table-column prop="standardCode" label="服务代码名称" />
      <el-table-column prop="displayName" label="服务类型" />
      <el-table-column
        prop="customPrice"
        label="当前价格"
        :formatter="({ customPrice }) => customPrice ?? '未设置'"
      />
      <el-table-column prop="defaultPrice" label="默认价格" />
      <el-table-column label="操作" fixed="right" width="260">
        <template #default="scope">
          <el-button
            link
            type="success"
            size="small"
            @click="createUserPrice(scope.row)"
          >
            创建用户特定价格
          </el-button>
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确定重置该用户服务类型的默认价格吗？"
            @confirm="resetUserPrice(scope.row)"
          >
            <template #reference>
              <el-button link type="warning" size="small">
                重置用户特定价格
              </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="tableStatus"
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick, computed } from "vue";
import { InfoFilled } from "@element-plus/icons-vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import {
  getUserPriceConfigs,
  resetUserPriceConfig,
  resetUserServicePrice
} from "@/api/adminPriceApi";
import { useTaskConfigHook } from "@/store/modules/taskConfig";
import CreateUserPriceDialog from "./components/CreateUserPriceDialog.vue";
import { message } from "@/utils/message";
import { useRemotePagedSelect } from "@/composables/useRemotePagedSelect";
import {
  userSelectFetcher,
  type UserItem
} from "@/composables/userSelectFetcher";
import { type ElSelect } from "element-plus";
import MulitServicePriceDialog from "./components/MulitServicePriceDialog.vue";

const taskConfigStore = useTaskConfigHook();
const formRef = ref();
const serviceTypes = computed(() => taskConfigStore.serviceTypes);
// 列表与加载状态
const loading = ref(false);
const delLoading = ref(false);

// 用户下拉：远程搜索 + 触底加载
const {
  list,
  loading: userLoading,
  onKeywordInput,
  onDropdownScroll,
  load
} = useRemotePagedSelect<UserItem>({
  pageSize: 20,
  autoLoad: false,
  debounceMs: 300,
  fetcher: userSelectFetcher
});

const userSelectRef = ref<InstanceType<typeof ElSelect> | null>(null);
let userDropdownWrapEl: HTMLElement | null = null;

function onUserDropdownVisibleChange(visible: boolean) {
  if (visible) {
    nextTick(() => {
      const popperEl = userSelectRef.value?.popperRef as
        | HTMLElement
        | undefined;
      // 在该选择器自己的 popper 里找 wrap
      userDropdownWrapEl =
        popperEl?.querySelector(".el-select-dropdown__wrap") ?? null;
      userDropdownWrapEl?.addEventListener("scroll", onDropdownScroll, {
        passive: true
      });
    });
  } else {
    userDropdownWrapEl?.removeEventListener("scroll", onDropdownScroll);
    userDropdownWrapEl = null;
  }
}

// 表单
const form = reactive<{
  userId: number;
  serviceType: string;
  keyword: string;
}>({
  userId: null,
  serviceType: "",
  keyword: ""
});

// 分页
const pagination = reactive({
  total: 0,
  pageSize: 20,
  currentPage: 1
});

// 表格数据
const tableData = ref<any[]>([]);
const createUserPriceDialogRef = ref();

const createUserPrice = (row: any) => {
  createUserPriceDialogRef.value?.open(row);
};
const mulitServicePriceDialogRef = ref();

const adjustUserCustom = () => {
  mulitServicePriceDialogRef.value?.open();
};

const resetAllUserPrice = async () => {
  try {
    if (form.userId == null)
      return message("请先选择用户", { type: "warning" });
    delLoading.value = true;
    await resetUserPriceConfig(form.userId);
    message("重置成功", { type: "success" });
    onSearch();
  } finally {
    delLoading.value = false;
  }
};

const resetUserPrice = async (row: any) => {
  try {
    await resetUserServicePrice(row.userId, row.standardCode);
    message("重置成功", { type: "success" });
    onSearch();
  } catch (e) {
    console.log(e);
  }
};

const tableStatus = ref(true);

const onSearch = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...form
    };
    const { data } = await getUserPriceConfigs(params);
    tableStatus.value = true;
    const { records, total, size, current } = data;

    tableData.value = (records || []).map((item: any) => {
      return {
        ...item,
        userId: form.userId,
        username: list.value.find(({ id }) => id === form.userId)?.username
      };
    });
    pagination.total = total ?? 0;
    pagination.pageSize = size ?? pagination.pageSize;
    pagination.currentPage = current ?? pagination.currentPage;
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};

const resetForm = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
  // 若有数据，默认选第一项
  form.userId = list.value[0]?.id ?? null;
  pagination.currentPage = 1;
  onSearch();
};

// 首次加载后，如果未选择用户则默认选第一项并搜索
onMounted(async () => {
  await load(1);
  if (list.value.length) {
    form.userId = list.value[0].id;
    onSearch();
  }
});
</script>

<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  gap: 20px;

  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>
